<template>
  <div>
    <el-card style="margin: 20px 20px">
      <el-form inline>
        <el-form-item>
          <el-input placeholder="用户名" v-model="searching" />
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click.prevent="searchUser"
          >查询</el-button
        ><el-button @click="clearSearch">清空</el-button>
      </el-form>
      <!-- //添加和批量删除 -->
      <div>
        <el-button type="primary" @click="addUser" v-myshow="'btn.User.add'"
          >添加</el-button
        >
        <el-button
          type="danger"
          :disabled="selectList.length === 0"
          @click="deleteUserList"
          >批量删除</el-button
        >
      </div>
      <div>
        <el-table
          style="margin-top: 20px"
          stripe
          border
          :data="userList"
          v-loading="loading"
          @selection-change="selectUser"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column label="序号" type="index" width="100">
          </el-table-column>
          <el-table-column label="用户名" prop="username"> </el-table-column>
          <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
          <el-table-column label="角色列表" prop="roleName" width="400">
          </el-table-column>
          <el-table-column label="创建时间" prop="gmtCreate"> </el-table-column>
          <el-table-column label="更新时间" prop="gmtModified">
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="info"
                icon="el-icon-user-solid"
                @click="toUserRole(scope.row)"
              ></el-button>
              <el-button
                type="primary"
                icon="el-icon-edit-outline"
                @click="addUser(scope.row)"
              ></el-button>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                ref="delBtn"
                @onConfirm="deleteUserItem(scope.row.id)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="total,  prev, pager,next,sizes,  ->,jumper"
          :total="pagination.total"
          :page-size="pagination.size"
          :page-sizes="[5, 10, 15]"
          :current-page="pagination.page"
          @current-change="currentPage"
          @size-change="sizeChange"
        >
        </el-pagination>
      </div>
      <!-- //新增和删除 -->
      <el-dialog :visible.sync="upDateDialogFlag" title="添加or新增">
        <el-form
          label-width="80px"
          :model="dialogForm"
          :rules="rules"
          ref="dialogFormRef"
        >
          <el-form-item label="用户名" prop="username" id="index"
            ><el-input v-model="dialogForm.username"
          /></el-form-item>
          <el-form-item label="用户昵称" prop="nickName" id="index"
            ><el-input v-model="dialogForm.nickName"
          /></el-form-item>
          <el-form-item
            label="用户密码"
            prop="password"
            id="index"
            v-if="passwordExist"
            ><el-input v-model="dialogForm.password" /></el-form-item
          >{{ passwordExist }}
        </el-form>
        <template #footer>
          <el-button @click="cancelFormData">取消</el-button>
          <el-button type="primary" @click="upDateUser()"
            >确定</el-button
          ></template
        >
      </el-dialog>
      <!-- 编辑 -->
      <el-dialog :visible.sync="roleFlag" title="设置角色">
        <el-form v-loading="loading" style="overflow: hidden">
          <el-form-item label="用户名" label-width="80px"
            ><el-input disabled v-model="userRoleName"></el-input
          ></el-form-item>
          <el-form-item label="角色列表" label-width="80px">
            <el-checkbox
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              v-model="checkAll"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="checkedList"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="role in allRolesList"
                :label="role.id"
                :key="role.id"
                >{{ role.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" @click="saveRole">保存</el-button>
            <el-button @click="roleFlag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import * as api from "@/api/acl/user.js";
import { MessageBox } from "element-ui";
export default {
  name: "User",
  data() {
    //密码规则
    const checkPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (!value || value.length < 6) {
        callback(new Error("密码长度不小于6"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      userList: [
        {
          deleted: false,
          gmtCreate: "",
          gmtModified: "",
          id: "",
          nickName: "",
          password: "",
          roleName: "",
          salt: null,
          token: null,
          username: "",
        },
      ],
      pagination: {
        page: 1,
        size: 5,
        total: 0,
      },
      loading: false,
      searching: "",
      upDateDialogFlag: false,
      dialogForm: {
        username: "",
        nickName: "",
        password: "",
        id: null,
      },
      rules: {
        username: [
          { required: true, message: "用户名必填", trigger: "blur" },
          { min: 4, message: "用户名不得小于4个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码必填", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
        ],
      },
      selectList: [],
      roleFlag: false,
      allRolesList: [
        {
          deleted: false,
          gmtCreate: "",
          gmtModified: "",
          id: "",
          remark: null,
          roleName: "",
        },
      ],
      assignRoles: [
        {
          deleted: false,
          gmtCreate: "",
          gmtModified: "",
          id: "",
          remark: null,
          roleName: "",
        },
      ],

      userRoleName: "",
      isIndeterminate: true,
      allCheckList: [],
      checkedList: [],
      checkAll: false,
      roleParams: {
        userId: "",
        roleId: "",
      },
    };
  },
  created() {},
  mounted() {
    this.getUserList();
  },
  computed: {
    passwordExist() {
      return this.dialogForm.id == undefined;
    },
    //弹窗全部
    // allCheckList() {
    //   return this.allRolesList.map((item) => item.id);
    // },
    // // //弹窗选中
    // checkedList() {
    //   return this.assignRoles.map((item) => item.id);
    // },
  },

  methods: {
    //获取数据
    async getUserList() {
      this.loading = true;
      const { page, size } = this.pagination;
      try {
        let result = await api.reqUserList(page, size);
        // console.log(result.data);

        this.userList = result.data.items;
        this.pagination.total = result.data.total;
        this.loading = false;
      } catch (e) {
        this.$message.error("获取数据失败");
      }
    },
    //页码
    currentPage(page) {
      // console.log("page", page);
      this.pagination.page = page;
      this.getUserList();
    },
    sizeChange(nowSize) {
      const { page, total } = this.pagination;
      this.pagination.size = nowSize;
      if (total / nowSize < page) {
        this.pagination.page = Math.floor(total / nowSize);
      }
      // console.log("page", page);

      this.getUserList();
    },
    //搜索
    searchUser() {
      if (this.searching === "") return this.$message.warning("不能为空");
      // console.log(this.searching);
      this.userList = this.userList.filter((item) => {
        // console.log(item);
        let newArr = item.username.includes(this.searching);
        this.pagination.total = newArr.length;
        return newArr;
      });
    },
    //清除
    clearSearch() {
      this.searching = "";
      this.getUserList();
    },
    //添加
    addUser(row) {
      this.upDateDialogFlag = true;
      const that = this;
      //整体表单校验

      setTimeout(() => {
        that.$refs.dialogFormRef.clearValidate();
      });
      if (!row.id) {
        delete this.dialogForm.id;
        this.dialogForm = {
          username: "",
          nickName: "",
          password: "",
          id: null,
        };
        this.pagination.page = 1;
      } else {
        this.dialogForm.id = row.id;
        this.dialogForm.username = row.username;
        this.dialogForm.password = row.password;
        this.dialogForm.nickName = row.nickName;
      }
      // console.log("");
    },
    //dialog关闭
    cancelFormData() {
      this.upDateDialogFlag = false;
    },
    //dialog提交
    async upDateUser() {
      this.$refs.dialogFormRef.validate((validate) => {
        //验证是否是正确
        // console.log("validate", validate);
        if (validate) {
          this.$message.success("校验成功");
        } else {
          this.$message.error("校验失败");
          return false;
        }
      });
      try {
        await api.reqUpdateUser(this.dialogForm);
        this.getUserList();
        this.upDateDialogFlag = false;
        this.$message.success("成功");
      } catch (e) {
        this.$message.error("提交失败");
      }
    },
    //删除
    async deleteUserItem(id) {
      try {
        // await this.$refs.delBtn.confirm;
        console.log(111111111);

        await api.reqDelete(id);
        this.$message.success("删除成功");
        this.getUserList();
      } catch (e) {
        this.$message.error("删除失败");
      }
    },
    //批量选中
    async selectUser(selection) {
      this.selectList = selection.map((item) => item.id);
      // console.log(this.selectList);
    },
    //批量删除
    async deleteUserList() {
      try {
        await MessageBox.confirm("此操作将永久数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        });
        await api.reqDeleteList(this.selectList);
        this.getUserList();
        this.$message.success("删除成功");
      } catch (e) {
        this.$message.error("删除失败");
      }
    },
    //权限弹窗
    async toUserRole(row) {
      this.loading = true;
      console.log("row", row);

      this.roleParams.userId = row.id;
      this.roleFlag = true;
      this.userRoleName = row.username;
      try {
        let result = await api.reqRoleList(row.id);

        // console.log("result", result);
        this.allRolesList = result.data.allRolesList;
        this.assignRoles = result.data.assignRoles;
        // console.log(this.checkedList);
        // console.log(this.allCheckList);
        this.allCheckList = this.allRolesList.map((item) => item.id);
        this.checkedList = this.assignRoles.map((item) => item.id);
        this.loading = false;
      } catch (e) {
        this.$message.error("获取列表失败");
      }
    },
    //打开role弹窗
    //全选事件
    handleCheckAllChange(value) {
      // console.log(value);
      this.checkedList = value ? this.allCheckList : [];
      this.isIndeterminate = false;
    },
    //其它选中模块
    handleCheckedCitiesChange(value) {
      // console.log(value);
      console.log(this.checkedList);

      this.checkAll = value.length === this.allRolesList.length;
      this.isIndeterminate =
        value.length > 0 && value.length < this.allRolesList.length;
    },
    async saveRole() {
      try {
        this.roleParams.roleId = this.checkedList.join(",");
        await api.reqCheckRole(this.roleParams);
        // console.log(this.checkedList.join(","));
        this.roleFlag = false;
        this.getUserList();
        this.$message.success("权限更改成功");
      } catch (e) {
        this.$message.error("权限更改出错");
      }
    },
  },
};
</script>
<style scoped lang="scss"></style>
